package com.study.manage.utils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.study.manage.dto.AjaxResponse;

public class HttpClient {

    private final static Logger logger = LoggerFactory.getLogger(HttpClient.class);

    private static JsonMapper jsonMapper = new JsonMapper();


    @SuppressWarnings("unchecked")
    public static AjaxResponse delete(String url, Map<String, Object> param) {
        AjaxResponse serverResponse = new AjaxResponse(true);
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            param = param == null ? new HashMap<>() : param;
            param.put("platform", "yunying");
            param.put("version", "1.0.0");
            StringBuilder paramUrl = new StringBuilder(url);
            String first = (url.indexOf("?") == -1) ? "?" : "&";
            if (param != null) {
                int i = 0;
                for (String key : param.keySet()) {
                    paramUrl.append(i == 0 ? first : "").append(key).append("=")
                            .append(param.get(key)).append("&");
                    i++;
                }
            }
            HttpDelete httpDelete = new HttpDelete(paramUrl.toString());
            logger.debug(new StringBuilder("send http request delete url:[").append(url)
                    .append("] ").append("param:[").append(jsonMapper.toJson(param)).append("]")
                    .toString());
            CloseableHttpResponse response = httpclient.execute(httpDelete);
            String json = EntityUtils.toString(response.getEntity());
            logger.debug(new StringBuilder("send http delete response return:[").append(json)
                    .append("]").toString());
            if (response.getStatusLine().getStatusCode() != 200) {
                Map<String, Object> map = jsonMapper.fromJson(json, Map.class);
                return serverResponse
                        .setMsg(map.containsKey("message") ? map.get("message").toString() : "");
            }
            serverResponse.setObj(json);
        } catch (Exception e) {
            logger.error("http 请求异常了 T_T", e);
            serverResponse.setMsg("系统繁忙！请稍候");
        } finally {
            try {
                if (httpclient != null) {
                    httpclient.close();
                }
            } catch (IOException e) {
                logger.error("http流关闭报错啦 T_T", e);
            }
        }
        return serverResponse;
    }


    @SuppressWarnings("unchecked")
    public static AjaxResponse post(String url, Object param) {
        AjaxResponse serverResponse = new AjaxResponse(true);
        CloseableHttpClient httpclient = HttpClients.createDefault();

        try {
            Map<String, Object> sysParam = new HashMap<>();
            sysParam.put("platform", "yunying");
            sysParam.put("version", "1.0.0");
            StringBuilder paramUrl = new StringBuilder(url);
            String first = (url.indexOf("?") == -1) ? "?" : "&";
            if (sysParam != null) {
                int i = 0;
                for (String key : sysParam.keySet()) {
                    paramUrl.append(i == 0 ? first : "").append(key).append("=")
                            .append(sysParam.get(key)).append("&");
                    i++;
                }
            }
            HttpPost httpPost = new HttpPost(paramUrl.toString());
            StringEntity params = new StringEntity(jsonMapper.toJson(param), "UTF-8");
            httpPost.addHeader("content-type", "application/json");
            httpPost.setEntity(params);
            logger.debug(new StringBuilder("send http request post url:[")
                    .append(paramUrl.toString()).append("] ").append("param:[")
                    .append(jsonMapper.toJson(param)).append("]").toString());
            CloseableHttpResponse response = httpclient.execute(httpPost);
            String json = EntityUtils.toString(response.getEntity());
            logger.debug(new StringBuilder("send http post response return:[").append(json)
                    .append("]").toString());
            if (response.getStatusLine().getStatusCode() != 200) {
                Map<String, Object> map = jsonMapper.fromJson(json, Map.class);
                return serverResponse
                        .setMsg(map.containsKey("message") ? map.get("message").toString() : "");
            }
            serverResponse.setObj(json);
        } catch (Exception e) {
            logger.error("http 请求异常了 T_T", e);
            serverResponse.setMsg("系统繁忙！请稍候");
        } finally {
            try {
                if (httpclient != null) {
                    httpclient.close();
                }
            } catch (IOException e) {
                logger.error("http流关闭报错啦 T_T", e);
            }
        }
        return serverResponse;
    }

    @SuppressWarnings("unchecked")
    public static AjaxResponse get(String url, Map<String, Object> param) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        AjaxResponse serverResponse = new AjaxResponse(true);
        try {
            param = param == null ? new HashMap<>() : param;

            if (!param.containsKey("platform"))
                param.put("platform", "yunying");
            if (!param.containsKey("version"))
                param.put("version", "1.0.0");
            StringBuilder paramUrl = new StringBuilder(url);
            String first = (url.indexOf("?") == -1) ? "?" : "&";
            if (param != null) {
                int i = 0;
                for (String key : param.keySet()) {
                    paramUrl.append(i == 0 ? first : "").append(key).append("=")
                            .append(param.get(key)).append("&");
                    i++;
                }
            }
            HttpGet httpGet = new HttpGet(paramUrl.toString());
            logger.debug(new StringBuilder("send http get request url[").append(paramUrl.toString())
                    .append("]").toString());
            CloseableHttpResponse response = httpclient.execute(httpGet);
            String json = EntityUtils.toString(response.getEntity());
            logger.debug(new StringBuilder("send http get response return:[").append(json)
                    .append("]").toString());
            if (response.getStatusLine().getStatusCode() != 200) {
                Map<String, Object> map = jsonMapper.fromJson(json, Map.class);
                return serverResponse
                        .setMsg(map.containsKey("message") ? map.get("message").toString() : "");
            }
            serverResponse.setObj(json);
        } catch (Exception e) {
            logger.error("http 请求异常了 T_T", e);
            serverResponse.setMsg("系统繁忙！请稍候");
        } finally {
            try {
                if (httpclient != null) {
                    httpclient.close();
                }
            } catch (IOException e) {
                logger.error("http流关闭报错啦 T_T", e);
            }
        }
        return serverResponse;

    }


    public static String getOriginal(String url, Map<String, Object> param) {
        String resMsg = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            param = param == null ? new HashMap<>() : param;
            param.put("platform", "yunying");
            param.put("version", "1.0.0");
            StringBuilder paramUrl = new StringBuilder(url);
            String first = (url.indexOf("?") == -1) ? "?" : "&";
            if (param != null) {
                int i = 0;
                for (String key : param.keySet()) {
                    paramUrl.append(i == 0 ? first : "").append(key).append("=")
                            .append(param.get(key)).append("&");
                    i++;
                }
            }
            HttpGet httpGet = new HttpGet(paramUrl.toString());
            logger.debug(new StringBuilder("send http get request url[").append(paramUrl.toString())
                    .append("]").toString());
            CloseableHttpResponse response = httpclient.execute(httpGet);
            String json = EntityUtils.toString(response.getEntity());
            logger.debug(new StringBuilder("send http get response return:[").append(json)
                    .append("]").toString());
            resMsg = json;
        } catch (Exception e) {
            logger.error("http 请求异常了 T_T", e);
        } finally {
            try {
                if (httpclient != null) {
                    httpclient.close();
                }
            } catch (IOException e) {
                logger.error("http流关闭报错啦 T_T", e);
            }
        }
        return resMsg;

    }

}
